package com.yunyouyi.cpicture.interfaces.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.yunyouyi.cpicture.infrastructure.annotation.AuthCheck;
import com.yunyouyi.cpicture.infrastructure.api.aliyunai.AliYunAiApi;
import com.yunyouyi.cpicture.infrastructure.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.yunyouyi.cpicture.infrastructure.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.yunyouyi.cpicture.infrastructure.common.DeleteRequest;
import com.yunyouyi.cpicture.infrastructure.common.Result;
import com.yunyouyi.cpicture.domain.user.constant.UserConstant;
import com.yunyouyi.cpicture.infrastructure.exception.BusinessException;
import com.yunyouyi.cpicture.infrastructure.exception.ErrorCode;
import com.yunyouyi.cpicture.infrastructure.exception.ThrowUtils;
import com.yunyouyi.cpicture.interfaces.assembler.PictureAssembler;
import com.yunyouyi.cpicture.interfaces.dto.picture.*;
import com.yunyouyi.cpicture.shared.auth.SpaceUserAuthManager;
import com.yunyouyi.cpicture.shared.auth.StpKit;
import com.yunyouyi.cpicture.shared.auth.annotation.SaSpaceCheckPermission;
import com.yunyouyi.cpicture.shared.auth.model.SpaceUserPermissionConstant;
import com.yunyouyi.cpicture.domain.picture.entity.Picture;
import com.yunyouyi.cpicture.interfaces.vo.picture.PictureTagCategory;
import com.yunyouyi.cpicture.domain.space.entity.Space;
import com.yunyouyi.cpicture.domain.user.entity.User;
import com.yunyouyi.cpicture.domain.picture.valueobject.PictureReviewStatusEnum;
import com.yunyouyi.cpicture.interfaces.vo.picture.PictureVO;
import com.yunyouyi.cpicture.application.service.PictureApplicationService;
import com.yunyouyi.cpicture.application.service.SpaceApplicationService;
import com.yunyouyi.cpicture.application.service.UserApplicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController {

    @Resource
    UserApplicationService userApplicationService;

    @Resource
    PictureApplicationService pictureApplicationService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private SpaceApplicationService spaceApplicationService;

    @Resource
    private AliYunAiApi aliYunAiApi;
    /**
     * 本地缓存
     */
    private final Cache<String, String> LOCAL_CACHE = Caffeine.newBuilder()
            .initialCapacity(1024)
            .maximumSize(10_000L)
            .expireAfterWrite(Duration.ofMinutes(5))
            .build();

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;


    /**
     * 文件上传
     *
     * @param file                   文件
     * @param pictureUploadDTO   文件上传请求
     * @param request                请求
     * @return {@link Result}<{@link PictureVO}>
     */
    @PostMapping("/upload")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public Result<PictureVO> uploadPicture(@RequestPart("file") MultipartFile file,
                                           PictureUploadDTO pictureUploadDTO,
                                           HttpServletRequest request) {
        User loginUser = userApplicationService.getLoginUser(request);
        PictureVO pictureVO = pictureApplicationService.uploadPicture(file, pictureUploadDTO, loginUser);
        pictureVO.setUser(userApplicationService.getUserVO(loginUser));
        return Result.success(pictureVO);
    }

    /**
     * 通过 URL 上传图片（可重新上传）
     */
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public Result<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadDTO pictureUploadDTO,
            HttpServletRequest request) {
        User loginUser = userApplicationService.getLoginUser(request);
        String fileUrl = pictureUploadDTO.getFileUrl();
        PictureVO pictureVO = pictureApplicationService.uploadPicture(fileUrl, pictureUploadDTO, loginUser);
        return Result.success(pictureVO);
    }

    /**
     * 删除图片  
     */
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public Result<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //传入业务模块
        boolean result = pictureApplicationService.deletePicture(deleteRequest.getId(), userApplicationService.getLoginUser(request));
        //清除缓存
        LOCAL_CACHE.invalidate(String.valueOf(deleteRequest.getId()));

        return Result.success(result);
    }

    /**
     * 更新图片（仅管理员可用）  
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public Result<Boolean> updatePicture(@RequestBody PictureUpdateDTO pictureUpdateDTO, HttpServletRequest request) {
        if (pictureUpdateDTO == null || pictureUpdateDTO.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换  
        Picture picture = PictureAssembler.toPictureEntity(pictureUpdateDTO);
        // 数据校验  
        pictureApplicationService.validPicture(picture);
        // 判断是否存在  
        long id = pictureUpdateDTO.getId();
        Picture oldPicture = pictureApplicationService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        //获取登录用户
        User loginUser = userApplicationService.getLoginUser(request);
        //填充审核参数
        pictureApplicationService.fileReviewParam(oldPicture, loginUser);
        // 操作数据库  
        boolean result = pictureApplicationService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }
    /**
     * 根据 id 获取图片（仅管理员可用）  
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public Result<Picture> getPictureById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库  
        Picture picture = pictureApplicationService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类  
        return Result.success(picture);
    }

    /**
     * 根据 id 获取图片（封装类）  
     */
    @GetMapping("/get/vo")
    public Result<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库  
        Picture picture = pictureApplicationService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验图片操作权限
        Long spaceId = picture.getSpaceId();
        Space space = null;
        if(spaceId != null){
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
            space = spaceApplicationService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
            //改为使用注解鉴权
//            pictureService.checkPictureAuth(picture, userService.getLoginUser(request));
        }
        //获取权限
        User loginUser = userApplicationService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        PictureVO pictureVO = pictureApplicationService.getPictureVO(picture, request);
        pictureVO.setPermissionList(permissionList);
        // 获取封装类
        return Result.success(pictureVO);
    }

    /**
     * 分页获取图片列表（仅管理员可用）  
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public Result<Page<Picture>> listPictureByPage(@RequestBody PictureQueryDTO pictureQueryDTO) {
        long current = pictureQueryDTO.getCurrent();
        long size = pictureQueryDTO.getPageSize();
        // 查询数据库  
        Page<Picture> picturePage = pictureApplicationService.page(new Page<>(current, size),
                pictureApplicationService.getQueryWrapper(pictureQueryDTO));
        return Result.success(picturePage);
    }

    /**
     * 分页获取图片列表（封装类）
     */
    @PostMapping("/list/page/vo")
    public Result<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryDTO pictureQueryDTO,
                                                             HttpServletRequest request) {
        long current = pictureQueryDTO.getCurrent();
        long size = pictureQueryDTO.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 空间权限校验
        Long spaceId = pictureQueryDTO.getSpaceId();
        if (spaceId == null) {
            // 公开图库
            // 普通用户默认只能看到审核通过的数据
            pictureQueryDTO.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryDTO.setNullSpaceId(true);
        } else {
            // 私有空间

            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
            //改为使用注解鉴权
//            User loginUser = userService.getLoginUser(request);
//            Space space = spaceService.getById(spaceId);
//            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
//            }
        }
        // 查询数据库
        Page<Picture> picturePage = pictureApplicationService.page(new Page<>(current, size),
                pictureApplicationService.getQueryWrapper(pictureQueryDTO));
        // 获取封装类
        return Result.success(pictureApplicationService.getPictureVOPage(picturePage, request));
    }

    /**
     * 分页获取图片列表（封装类）
     */
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    @PostMapping("/list/page/vo/cache")
    public Result<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryDTO pictureQueryDTO,
                                                             HttpServletRequest request) {
        //空间权限校验
        Long spaceId = pictureQueryDTO.getSpaceId();
        if(spaceId == null){
            //这是公开图库
            //普通用户只能查审核通过的图片
            pictureQueryDTO.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryDTO.setNullSpaceId(true);
        }else{
            //这是私有图库
            User loginUser = userApplicationService.getLoginUser(request);
            Space space = spaceApplicationService.getById(spaceId);
            ThrowUtils.throwIf(space==null,ErrorCode.NOT_FOUND_ERROR,"空间不存在");
            //判断是否为空间本人
            if(!space.getUserId().equals(loginUser.getId())){
                ThrowUtils.throwIf(!loginUser.isAdmin(),ErrorCode.NO_AUTH_ERROR,"无权限");
            }
        }
        long current = pictureQueryDTO.getCurrent();
        long size = pictureQueryDTO.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        //序列化key
        String key = JSONUtil.toJsonStr(pictureQueryDTO);
        // 缩减key的长度
        String HashKey = DigestUtils.md5DigestAsHex(key.getBytes());
        //本地缓存key
        String cacheKey = String.format("listPictureVOByPage:%s", HashKey);
        String redisKey = String.format("Cpicture:listPictureVOByPage:%s", HashKey);
        //1. 本地缓存取出数据
        String cacheValue = LOCAL_CACHE.getIfPresent(cacheKey);
        if(cacheValue != null){
            Page<PictureVO> pictureVOPage = JSONUtil.toBean(cacheValue, Page.class);
            return Result.success(pictureVOPage);
        }
        // 2. 为null去redis里检索
        // 从redis缓存中取出数据
        ValueOperations<String,String> valueOps = stringRedisTemplate.opsForValue();
        String value = valueOps.get(redisKey);
        //不为空返回数据
        if(value != null){
            Page<PictureVO> pictureVOPage = JSONUtil.toBean(value, Page.class);
            //加载到本地缓存
            LOCAL_CACHE.put(cacheKey,value);
            return Result.success(pictureVOPage);
        }
        //3. 为空则查数据库并加载到redis缓存中
        // 查询数据库
        Page<Picture> picturePage = pictureApplicationService.page(new Page<>(current, size),
                pictureApplicationService.getQueryWrapper(pictureQueryDTO));
        // 获取封装类
        Page<PictureVO> pictureVOPage = pictureApplicationService.getPictureVOPage(picturePage, request);
        //设置过期时间为10-30分钟防止雪崩
        String jsonStr = JSONUtil.toJsonStr(pictureVOPage);
        LOCAL_CACHE.put(cacheKey, jsonStr);
        int cacheExpireTime = RandomUtil.randomInt(1000, 3000);
        valueOps.set(redisKey, jsonStr,cacheExpireTime, TimeUnit.SECONDS);
        return Result.success(pictureVOPage);
    }
    /**
     * 编辑图片（给用户使用）  
     */
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public Result<Boolean> editPicture(@RequestBody PictureEditDTO pictureEditDTO, HttpServletRequest request) {
        if (pictureEditDTO == null || pictureEditDTO.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换  
        Picture picture = PictureAssembler.toPictureEntity(pictureEditDTO);
        // 设置编辑时间  
        picture.setEditTime(new Date());
        // 数据校验
        pictureApplicationService.validPicture(picture);
        User loginUser = userApplicationService.getLoginUser(request);
        // 判断是否存在  
        long id = pictureEditDTO.getId();
        Picture oldPicture = pictureApplicationService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验图片操作权限
        //改为使用注解鉴权 pictureService.checkPictureAuth(oldPicture, loginUser);
        // 填充审核信息
        pictureApplicationService.fileReviewParam(oldPicture, loginUser);
        // 操作数据库  
        boolean result = pictureApplicationService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }
    /**
     * 获取图片标签和分类
     */
    @GetMapping("/tag_category")
    public Result<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意","原创","原著","同人","AI");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报","画家推荐");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return Result.success(pictureTagCategory);
    }
    /**
     * 审核图片（管理员使用）
     * @param pictureReviewDTO
     * @return
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public Result<Boolean> doPictureReview (@RequestBody PictureReviewDTO pictureReviewDTO,
                                                       HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewDTO == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        return Result.success(pictureApplicationService.doPictureReview(pictureReviewDTO, loginUser));
    }
    @PostMapping("/upload/batch")
    public Result<Integer> uploadPictureByBatch(
            @RequestBody PictureUploadByBatchDTO pictureUploadByBatchDTO,
            HttpServletRequest request){
        ThrowUtils.throwIf(pictureUploadByBatchDTO == null, ErrorCode.PARAMS_ERROR);
        return Result.success(pictureApplicationService.uploadPictureByBatch(pictureUploadByBatchDTO, userApplicationService.getLoginUser(request)));
    }
    /**
     * 编辑图片（批量）
     */
    @PostMapping("/edit/batch")
    public Result<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchDTO pictureEditByBatchDTO, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditByBatchDTO == null, ErrorCode.PARAMS_ERROR, "参数错误");
        User loginUser = userApplicationService.getLoginUser(request);
        pictureApplicationService.editPictureByBatch(pictureEditByBatchDTO,loginUser);
        return Result.success(true);
    }

    /**
     * AI扩图请求
     */
    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public Result<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(@RequestBody CreatePictureOutPaintingTaskDTO createOutPaintingTaskDTO,
                                                                              HttpServletRequest request){
        ThrowUtils.throwIf(createOutPaintingTaskDTO == null || createOutPaintingTaskDTO.getPictureId() == null, ErrorCode.PARAMS_ERROR, "AI扩图参数错误");
        return Result.success(pictureApplicationService.createPictureOutPainting(createOutPaintingTaskDTO, userApplicationService.getLoginUser(request)));
    }

    /**
     * 查询AI扩图结果
     */
    @GetMapping("/out_painting/get_task")
    public Result<GetOutPaintingTaskResponse> getPictureOutPaintingTask(@RequestParam("taskId") String taskId){
        ThrowUtils.throwIf(taskId == null, ErrorCode.PARAMS_ERROR, "AI扩图参数错误");
        GetOutPaintingTaskResponse outPaintingTask = aliYunAiApi.getOutPaintingTask(taskId);
        return Result.success(outPaintingTask);
    }
}







